package com.wsoft.portal.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wsoft.core.service.CommonConfigService;
import com.wsoft.core.utils.LoginUserUtil;
import com.wsoft.core.vo.ConfigQuery;
import com.wsoft.portal.entity.PortalModuleEntity;
import com.wsoft.portal.entity.PortalModuleSubEntity;
import com.wsoft.portal.entity.PortalOrgMemberEntity;
import com.wsoft.portal.entity.PortalThemeEntity;
import com.wsoft.portal.enums.RenderTypeEnum;
import com.wsoft.portal.layout.Block;
import com.wsoft.portal.manager.PortalModuleManager;
import com.wsoft.portal.manager.PortalModuleSubManager;
import com.wsoft.portal.manager.PortalOrgMemberManager;
import com.wsoft.portal.manager.PortalThemeManager;
import com.wsoft.portal.mapper.PortalModuleMapper;
import com.wsoft.portal.query.module.*;
import com.wsoft.portal.service.IPortalModuleService;
import com.wsoft.portal.utils.ModulePageLayoutUtil;
import com.wsoft.portal.utils.PortalUtil;
import com.wsoft.portal.vo.module.ModuleLayoutVO;
import com.wsoft.portal.vo.module.RenderModuleSubVO;
import com.wsoft.portal.vo.module.RenderModuleVO;
import com.wsoft.portal.vo.module.RenderVO;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 空间类型 服务实现类
 * </p>
 *
 * @author Z001
 * @since 2024年12月27日 10:02:24
 */
@Service
public class PortalModuleServiceImpl extends ServiceImpl<PortalModuleMapper, PortalModuleEntity> implements IPortalModuleService {

    @Resource
    private PortalThemeManager themeManager;
    @Resource
    private PortalModuleManager moduleManager;
    @Resource
    private PortalModuleSubManager subManager;
    @Resource
    private PortalOrgMemberManager orgMemberManager;
    @Resource
    private CommonConfigService commonConfigService;
    @Resource
    private PortalUtil portalUtil;


    /**
     * config 门户默认配置
     */
    private final String PORTAL_DEFAULT_CONFIG = "portal_default_config";

    /**
     * 新增板块
     *
     * @return
     * @Param Query
     */
    @Override
    public boolean insertModule(ModuleInsertQuery query) {
        //表体高度取config,透明度取默认值
        ConfigQuery configQuery = new ConfigQuery();
        configQuery.setCode(PORTAL_DEFAULT_CONFIG);
        Map<String, String> map = commonConfigService.getConfigValue(configQuery);

        //查询默认的每列宽度
        String columnWidths = map.get("width");
        //查询当前portalId下所有的板块
        List<PortalModuleEntity> moduleList = moduleManager.getByPortalId(query.getPortalId());

        Block block = ModulePageLayoutUtil.addModule(columnWidths,handlerModuleList(moduleList));

        PortalModuleEntity module = Convert.convert(PortalModuleEntity.class, query);
        module.setBodyHeight(StrUtil.isBlank(map.get("bodyHeight")) ? 0 : Convert.toInt(map.get("bodyHeight")));
        //表体背景透明度 默认为0
        module.setBodyBgOpacity(new BigDecimal("0.8"));
        module.setTitleBgOpacity(new BigDecimal("0.8"));
        module.setAxisX(new BigDecimal(block.x));
        module.setAxisY(new BigDecimal(block.y));
        module.setTitleHidden(1);
        module.setWidth(block.w);
        module.setHeight(block.h);
        //默认为1
        module.setWidthCount(1);

        boolean b = moduleManager.save(module);
        if(b){
            portalUtil.updateExtendParent(query.getPortalId());
        }
        return b;
    }

    /**
     * 修改板块
     *
     * @param query
     * @return
     */
    @Override
    public boolean updateModule(ModuleUpdateQuery query) {
        boolean b = moduleManager.updateById(Convert.convert(PortalModuleEntity.class, query));
        if(b){
            portalUtil.updateExtendParent(query.getPortalId());
        }
        return b;
    }

    /**
     * 获取板块详情
     *
     * @param id
     * @return
     */
    @Override
    public PortalModuleEntity getModuleInfo(Long id) {
        return moduleManager.getById(id);
    }

    /**
     * 删除板块
     *
     * @param id
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteModule(Long id) {
        PortalModuleEntity entity = moduleManager.getById(id);
        subManager.removeByModuleId(id);
        moduleManager.removeById(id);

        portalUtil.updateExtendParent(entity.getPortalId());
        return true;
    }

    /**
     * 修改板块宽高和sort
     * @param query
     * @return
     */
    @Override
    public boolean updateWhSort(List<ModuleWidthHeightListQuery> query) {
        List<PortalModuleEntity> list = new ArrayList<>();

        for (ModuleWidthHeightListQuery widthHeightListQuery : query) {
            PortalModuleEntity module = Convert.convert(PortalModuleEntity.class, widthHeightListQuery);
            list.add(module);
        }
        boolean b = moduleManager.updateBatchById(list);
        if(b){
            portalUtil.updateExtendParentSub(list.get(0).getId());
        }
        return b;
    }


    /**
     * 渲染
     *
     * @param query
     * @return
     */
    @Override
    public RenderVO render(RenderQuery query) {
        RenderVO renderVO = new RenderVO();
        renderVO.setPortalId(query.getPortalId());
        //查询config 整体布局
        ConfigQuery configQuery = new ConfigQuery();
        configQuery.setCode(PORTAL_DEFAULT_CONFIG);
        Map<String, String> map = commonConfigService.getConfigValue(configQuery);
        ModuleLayoutVO layoutVO = new ModuleLayoutVO();
        layoutVO.setColumn(Integer.valueOf(map.get("column")));
        layoutVO.setWidth(map.get("width"));
        renderVO.setModuleLayout(layoutVO);

        List<RenderModuleVO> moduleVOList = new ArrayList<>();
        //查询 module 模块
        List<PortalModuleEntity> moduleEntityList = moduleManager.getByPortalId(query.getPortalId());
        for (PortalModuleEntity entity : moduleEntityList) {
            RenderModuleVO convert = Convert.convert(RenderModuleVO.class, entity);
            //查询sub模块
            List<PortalModuleSubEntity> subList = subManager.getParIdList(Collections.singletonList(convert.getId()));
            if(CollUtil.isNotEmpty(subList)){
                List<RenderModuleSubVO> collect = subList.stream().map(item -> Convert.convert(RenderModuleSubVO.class, item)).collect(Collectors.toList());
                convert.setSubList(collect);
            }else{
                convert.setSubList(new ArrayList<>());
            }
            moduleVOList.add(convert);
        }

        renderVO.setModuleVOList(moduleVOList);
        return renderVO;
    }

    @Override
    public RenderVO userRender(UserRenderQuery query,String type) {
        Long orgId = null;
        PortalThemeEntity themeEntity = themeManager.getByCode(query.getThemeCode());
        PortalOrgMemberEntity portal = null;
        if(type.equals(RenderTypeEnum.USER.getType())){
            portal = orgMemberManager.getByThemeId(themeEntity.getId(),null, LoginUserUtil.getUserInfo().getLoginUserVO().getId());
            if(null == portal){
                portal = orgRender(themeEntity.getId(), LoginUserUtil.getUserInfo().getLoginUserVO().getLoginOrgId());
                //如果渲染的时候 是查询的上级,则复制一份给当前用户
                portal = portalUtil.copyDefaultTheme(themeEntity.getId(),portal,null, LoginUserUtil.getUserInfo().getLoginUserVO().getId());
            }
        }else{
            if(null == query.getOrgId()){
                orgId = LoginUserUtil.getUserInfo().getLoginUserVO().getLoginOrgId();
            }else{
                orgId = query.getOrgId();
            }
            portal = orgMemberManager.getByThemeId(themeEntity.getId(),orgId, null);
            if(null == portal){
                portal = orgRender(themeEntity.getId(), orgId);
                //如果渲染的时候 是查询的上级,则复制一份给当前组织
                portal = portalUtil.copyDefaultTheme(themeEntity.getId(),portal,orgId,null);
            }
        }
        RenderQuery renderQuery = new RenderQuery();
        renderQuery.setPortalId(portal.getId());
        return render(renderQuery);
    }

    @Override
    public boolean recover(PortalRecoverQuery query,String type) {
        PortalThemeEntity themeEntity = themeManager.getByCode(query.getThemeCode());
        if(type.equals(RenderTypeEnum.USER.getType())){
            return orgMemberManager.removeByThemeId(themeEntity.getId(),null,LoginUserUtil.getUserInfo().getLoginUserVO().getId());
        }else{
            return orgMemberManager.removeByThemeId(themeEntity.getId(),query.getOrgId(),null);
        }
    }

    // ################################## 私有方法  ##################################

    /**
     * 查询组织
     * @param themeId
     * @param curOrgId
     * @return
     */
    public PortalOrgMemberEntity orgRender(Long themeId,Long curOrgId){
      return  portalUtil.getParentPortal(themeId, curOrgId);
    }

    /**
     * 处理moduleList
     * @param moduleList
     * @return
     */
    private List<Block> handlerModuleList( List<PortalModuleEntity> moduleList){
        List<Block> blocks = new ArrayList<>();
        if(CollUtil.isEmpty(moduleList)){
            return blocks;
        }
        for (PortalModuleEntity entity : moduleList) {
            Block block = new Block(entity.getAxisX().intValue(),entity.getAxisY().intValue(),entity.getWidth(),entity.getHeight());
            blocks.add(block);
        }
        return blocks;
    }

}
